package com.study.wumeng.androidandh5;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author WuMeng
 */
public class JavaAndJsCallActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etNumber;
    private EditText etPassword;
    private Button btnLogin;
    private WebView webView;

    private void findViews() {
        etNumber = (EditText)findViewById( R.id.et_number );
        etPassword = (EditText)findViewById( R.id.et_password );
        btnLogin = (Button)findViewById( R.id.btn_login );

        btnLogin.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if ( v == btnLogin ) {
            Login();
        }
    }

    private void Login() {

        String name = etNumber.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "账号和密码不能为空!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "登录成功!", Toast.LENGTH_SHORT).show();
            login(name);
        }
    }

    private void login(String name) {
        webView.loadUrl("javascript:javaCallJs(" + "'" + name + "'" +")");
        setContentView(webView);
    }


    private void initWebView() {
        // 加载网页 -H5，HTML，自定义浏览器
        webView = new WebView(this);

        WebSettings webSettings = webView.getSettings();
        // 设置支持JS
        webSettings.setJavaScriptEnabled(true);

        // 调用内部浏览器，不调用外部浏览器
        webView.setWebViewClient(new WebViewClient());

        // 添加JavaScript接口
        // 以后JS通过Android字段调用AndroidAndJsInterface中的任何方法
        webView.addJavascriptInterface(new AndroidAndJsInterface(),"Android");

        // 加载网络的网页---本地的网页
        //webView.loadUrl("http://www.atguigu.com/");
        webView.loadUrl("file:///android_asset/JavaAndJavaScriptCall.html");
    }

    class AndroidAndJsInterface {
        /**
         * 将会被JS调用
         */
        @JavascriptInterface
        public void showToast() {
            Toast.makeText(JavaAndJsCallActivity.this, "我是Android代码，我被JS代码调用了", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_java_and_js_call);
        findViews();
        // 初始化WebView
        initWebView();
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
